import json
import os
from typing import List, Dict, Optional
from dataclasses import dataclass, asdict
from pathlib import Path

@dataclass
class GitAccount:
    id: str
    name: str
    username: str
    email: str
    password_encrypted: str = ""
    is_default: bool = False

class ConfigManager:
    def __init__(self, config_file: str = "git_accounts.json"):
        self.config_file = Path(config_file)
        self.accounts: List[GitAccount] = []
        self.load_config()
    
    def load_config(self) -> None:
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.accounts = [GitAccount(**account) for account in data.get('accounts', [])]
            except (json.JSONDecodeError, KeyError) as e:
                print(f"配置文件加载失败: {e}")
                self.accounts = []
        else:
            self.accounts = []
    
    def save_config(self) -> None:
        config_data = {
            "accounts": [asdict(account) for account in self.accounts],
            "version": "1.0"
        }
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"配置文件保存失败: {e}")
    
    def add_account(self, account: GitAccount) -> bool:
        if any(acc.id == account.id for acc in self.accounts):
            return False
        self.accounts.append(account)
        self.save_config()
        return True
    
    def update_account(self, account: GitAccount) -> bool:
        for i, acc in enumerate(self.accounts):
            if acc.id == account.id:
                self.accounts[i] = account
                self.save_config()
                return True
        return False
    
    def delete_account(self, account_id: str) -> bool:
        self.accounts = [acc for acc in self.accounts if acc.id != account_id]
        self.save_config()
        return True
    
    def get_account(self, account_id: str) -> Optional[GitAccount]:
        for account in self.accounts:
            if account.id == account_id:
                return account
        return None
    
    def get_all_accounts(self) -> List[GitAccount]:
        return self.accounts.copy()
    
    def get_default_account(self) -> Optional[GitAccount]:
        for account in self.accounts:
            if account.is_default:
                return account
        return None
    
    def set_default_account(self, account_id: str) -> bool:
        for account in self.accounts:
            account.is_default = (account.id == account_id)
        self.save_config()
        return True